package com.password.desktop.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.password.desktop.exception.FileNotFileException;
import com.password.desktop.exception.NoLoginException;
import com.password.desktop.util.SysUtil;
import com.password.entity.User;
import com.password.services.TextSecretService;
import com.password.util.RSAEncryptUtil;

public class SavedTextSecretService {
	private static final String SAVED_FILE_SUFFIX = ".textSecret";
	LoginService loginService = LoginService.builderLoginService();
	TextSecretService secretService = TextSecretService.getTextSecretService();

	private static final SavedTextSecretService SA_TEXT_SECRET_SERVICE = new SavedTextSecretService();

	private SavedTextSecretService() {
	}

	public static SavedTextSecretService build() {
		return SA_TEXT_SECRET_SERVICE;
	}

	/**
	 * 
	 * 加密指定文本
	 * 
	 * @author yzh
	 * @date 2020年6月6日
	 * 
	 */
	public String encordText(String text) throws Exception {
		User userD = getLoginUser();
		String publicKey = userD.getRsaKey();
		return RSAEncryptUtil.encrypt(text, publicKey);
	}

	/**
	 * 保存密文
	 * 
	 * @description
	 * @author yzh
	 * @date 2020年6月6日
	 */
	public void saveSecret(String item, String secret) throws Exception {
		File path = getUserdHome();
		if (!path.exists()) {
			path.mkdirs();
		}
		File saveFile = new File(path, item + SAVED_FILE_SUFFIX);
		if (!saveFile.exists()) {
			saveFile.createNewFile();
		}
		try (OutputStream out = new FileOutputStream(saveFile);) {
			out.write(secret.getBytes("UTF-8"));
		}
	}

	/**
	 * 获取文档,正常清空下该Map有固定的二个key值。
	 * 
	 * <pre>
	 * key为：encrypt是代表是加密的文本
	 * key为：decrypt是解密后的文本
	 * </pre>
	 * 
	 * @description
	 * @author yzh
	 * @date 2020年6月6日
	 */
	public Map<String, String> getTextForItem(String item) throws Exception {
		User userD = getLoginUser();
		Map<String, String> result = new HashMap<>();
		File saveFile = new File(getUserdHome(), item + SAVED_FILE_SUFFIX);
		if (!saveFile.exists()) {
			throw new FileNotFileException("保存的文件不存在或者已经删除");
		}
		try (InputStream in = new FileInputStream(saveFile);) {
			byte[] data = new byte[in.available()];
			in.read(data);
			String d = new String(data, "UTF-8");
			String decordText = secretService.decordText(userD, d);
			result.put("encrypt", d);
			result.put("decrypt", decordText);
			return result;
		}
	}

	/**
	 * 获取用户保存的文档
	 * 
	 * @description
	 * @author yzh
	 * @date 2020年6月6日
	 */
	public List<String> getItems() throws Exception {
		List<String> result = new ArrayList<>();
		addItem(result, getUserdHome());
		return result;
	}

	private void addItem(List<String> items, File file) {
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			for (File f : listFiles) {
				addItem(items, f);
			}
		} else {
			String name = file.getName();
			if (name.endsWith(SAVED_FILE_SUFFIX)) {
				items.add(name.substring(0, name.lastIndexOf(SAVED_FILE_SUFFIX)));
			}
		}
	}

	/**
	 * 根据密文获取解密后的数据
	 * 
	 * @description
	 * @author yzh
	 * @date 2020年6月6日
	 */
	public String decodeText(String secret) throws Exception {
		User userD = getLoginUser();
		return secretService.decordText(userD, secret);
	}

	private User getLoginUser() {
		User userD = loginService.getCurrentUser();
		if (userD == null) {
			throw new NoLoginException("用户未登录或登录失效");
		}
		return userD;
	}

	private File getUserdHome() {
		User userD = getLoginUser();
		return new File(SysUtil.USER_SAVE_PATH, userD.getUserName());
	}

	public boolean deleteItem(String item) {
		File path = getUserdHome();
		File saveFile = new File(path, item + SAVED_FILE_SUFFIX);
		if (saveFile.exists()) {
			return saveFile.delete();
		}
		throw new FileNotFileException("文件不存在");

	}

}
